<?php

namespace App\Http\Controllers\ShopAdmin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Models\Goods;
use App\Models\Category;
use App\Models\Brand;
use App\Models\Activity;
use App\Models\RecommendPosition;
use App\Models\GoodsContent;
use App\Models\GoodsGallery;
use App\Models\CategoryBrand;
use App\Models\Shop;
use App\Models\SearchKeywords;
use App\Models\ActivityGoods;
use App\Models\GoodsStockHistory;
use App\Models\ProductSku;
use App\Models\GoodsEorderInfo;
use App\Interfaces\SolrService;
use App\Interfaces\CategoryService;
use App\Interfaces\StockService;
use App\Interfaces\GoodsStockHistoryService;

use App\Commands\OperationLogCommand;

use App\Http\Requests\ShopAdmin\Goods\GoodsCreateRequest;
use App\Http\Requests\ShopAdmin\Goods\GoodsUpdateRequest;
use App\Http\Requests\ShopAdmin\Goods\GoodsStockOpreationRequest;
use App\Http\Requests\ShopAdmin\Goods\GoodsEorderInfoRequest;

use Session,Auth,DB,Redirect;

use App\Exceptions\Interfaces\StockServiceException;

class GoodsController extends Controller
{

    private $shop_id;

    public function __construct()
    {

        $this->shop_id = Session::get('userShopId');
    }

    /**
     * 商品列表页.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, Category $category)
    {

        //品牌数组

        $brandInfo = Brand::all();

        $brandArr = ['0'=>'选择品牌'];

        foreach ($brandInfo as $key => $value) {

            $brandArr[$value->brand_id] = $value->brand_name;

        }//end foreach()


        //是否上下架
        $isOnSaleArr = ['0'=>'所有上下架', '1'=>'上架', '2'=>'下架'];

        $typeArr = ['-1'=>'选择类型', '0'=>'一般商品', '1'=>'e贸易商品'];

        $goodsNumberArr = ['All'=>'库存','0-50'=>'0-50','50-100'=>'50-100','100-200'=>'100-200','200-500'=>'200-500','500-'=>'500以上'];

        $search = array('cat_id'=>0, 'brand_id'=>0, 'type'=>-1, 'is_on_sale'=>0,'goods_number'=>'All', 'goods_name'=>'', 'goods_sn'=>'');

        $query =  Goods::orderBy('add_time', 'desc')->orderBy('goods_id', 'desc');

        $query = $query->where('shop_id', Session::get('userShopId'));

        if ($request->get('cat_id')!='' && $request->get('cat_id')!=0){

            $query = $query->where('cat_id', $request->get('cat_id'));

            $search['cat_id'] = $request->cat_id;
        }//end if()


        if ($request->get('brand_id')!='' && $request->get('brand_id')!=0){

            $query = $query->where('brand_id', $request->get('brand_id'));

            $search['brand_id'] = $request->brand_id;
        }//end if()


        if ($request->get('type')!='' && $request->get('type')!=-1){

            $query = $query->where('type', $request->get('type'));

            $search['type'] = $request->type;
        }//end if()


        if (!empty($request->get('goods_name'))){

            $goods_name = $request->goods_name;

            $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);

            $query = $query->where('goods_name', 'like', "%".trim($goods_name)."%");

            $search['goods_name'] = $request->goods_name;
        }//end if()

        if (!empty($request->get('goods_sn'))){
            $goods_sn = $request->goods_sn;

            $goods_sn = preg_replace('~\s{2,}~', ' ', $goods_sn);

            $query = $query->where('goods_sn', 'like', "%".$goods_sn."%");

            $search['goods_sn'] = $request->goods_sn;

        }//end if()

        if ($request->get('is_on_sale')!='' && $request->get('is_on_sale')!=0){

            $query = $query->where('is_on_sale', $request->get('is_on_sale'));

            $search['is_on_sale'] = $request->is_on_sale;

        }//end if()

        if ($request->get('goods_number')!='' && $request->get('goods_number')!='All'){

            $goods_number = explode('-',$request->get('goods_number'));

            if($goods_number[1]){

                $query = $query->where('goods_number','>=',$goods_number[0]);

                $query = $query->where('goods_number','<=',$goods_number[1]);
            }else{

                $query = $query->where('goods_number','>=',$goods_number[0]);
            }

            $search['goods_number'] = $request->goods_number;

        }//end if()

        $goods = $query->paginate(10);

        foreach ($goods as $key => $value) {

            $cat_id = $value->cat_id;

            $categorys = Category::where('cat_id', $cat_id)->get();

            $goods[$key]['cat_name'] = @$categorys[0]->cat_name;
        }//end foreach()

        //活动数组
        $activityArr = ['0'=>'请选择活动'];

        $activityInfo = Activity::get();

        foreach ($activityInfo as $key => $value) {

            $activityArr[$value->id] = $value->name;
        }//end foreach()


        //推荐位置数组
        $recommendArr = ['0'=>'请选择推荐位置'];

        $recommendInfo = RecommendPosition::get();

        foreach ($recommendInfo as $key => $value) {

            $recommendArr[$value->id] = $value->name;

        }//end foreach()


        return view('shop_admin.goods.index',compact(['goods','category', 'brandArr', 'typeArr', 'isOnSaleArr', 'activityArr', 'recommendArr','goodsNumberArr','search']));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Goods $goods,Category $category)
    {

        //品牌数组
        $brandInfo = Brand::all();

        $brandArr = ['0'=>'=请选择品牌='];


        //店铺数组
        $shopInfo = Shop::all();

        $shopArr = ['0'=>'=选择店铺='];

        foreach ($shopInfo as $key => $value) {

            $shopArr[$value->id] = $value->shop_name;
        }//end foreach()

        $typeArr = ['0'=>'一般商品', '1'=>'e贸易商品'];

        return view('shop_admin.goods.create',compact(['goods','category', 'brandArr', 'shopArr', 'typeArr']));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(GoodsCreateRequest $goodsRequest,CategoryService $categoryService,GoodsEorderInfo $goodsEorderInfo ,StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService)
    {

        $requestParam = $goodsRequest->all();

        $goods_sn = $goodsRequest->get('goods_sn');

        $type = $goodsRequest->get('type');

        $goods_name = $goodsRequest->goods_name;

        $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);       //将商品名字中间多个空格替换为一个空格

        $requestParam['goods_name'] = $goods_name;

        $requestParam['shop_id'] = $this->shop_id;

        $goodsArr = Goods::lists('goods_sn')->toArray();

        $is_goods = in_array($goods_sn,$goodsArr);

        if($is_goods){

            return Redirect::back()->withInput()->with('message','该货号已存在');
        }

        if($type==1){

            $egoodsArr = GoodsEorderInfo::lists('goods_sn')->toArray();

            $is_goods_sn = in_array($goods_sn,$egoodsArr);

            if($is_goods_sn){

                $goods = Goods::create($requestParam);
            }else{

                return Redirect::back()->withInput()->with('message','该货号未备案');
            }
        }else{

            $goods = Goods::create($requestParam);
        }

        $this->dispatch(

            new OperationLogCommand('添加商品', 'Goods','goods_id:'.$goods->goods_id)
        );


        if ($goods){

            $requestParam['goods_id'] = $goods->goods_id;

            $goods_id = $goods->goods_id;

            $goods_sn = $goods->goods_sn;

            $goods_name = $goods->goods_name;

            $cat_id = $goods->cat_id;

            $brand_id = $goods->brand_id;

            $keywords = $goods->keywords;

            $goods_number = $goods->goods_number;

            if(!empty($goods_number) && $goods_number>0){

                $user_id = Auth::user()->id;

                $operation = 1;

                $describe = '添加商品时增加库存，数量：'.$goods_number;

                $goodsStockHistoryService->updateStockHistory($goods_id, $user_id, $describe, $goods_number, $operation);
            }


            $goods_content = @$goodsRequest->goods_content;

            if(!empty($goods_content)){

                $goodsContent = GoodsContent::find($goods_id);

                if($goodsContent){

                    $goodsContents = GoodsContent::where('goods_id', $goods_id)->update(['goods_content'=>$goods_content]);
                }else{

                    $goodsContents = GoodsContent::insert(['goods_id' => $goods_id, 'goods_content' => $goods_content]);
                }//end if()
            }//end if()

            //创建商品相册
            $requestGallery = $goodsRequest->get('goods_gallery');

            $requestGallery['goods_id'] = $goods_id;

            GoodsGallery::create($requestGallery);


            $category = Category::find($cat_id);

            if(!count($category)){

                $cat_id = 0;

            }//end if()


            $brand = Brand::find($brand_id);

            if(!count($brand)){

                $brand_id = 0;
            }//end if()


            if(!empty($keywords)){

                $keywords = preg_replace("/((\n)|(\s)|(\t)|(，))/", ',', $keywords);

                $keywords = trim($keywords, ',');

                $keywordsStr = trim($keywords);
            }else{

                $keywordsStr = '';
            }//end if()

            $this->keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService);
        }//end if()

        return Redirect('shop_admin/goods');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($goods_id,Category $category, Request $request)
    {

        $back_url = '';

        if($request->back_url){

            $back_url = $request->back_url;
        }

        $goods = Goods::findOrNew($goods_id);

        if(!empty($goods)){

            $goods_id = $goods->goods_id;

            $goodsContent = GoodsContent::find($goods_id);

            if($goodsContent){

                $goods_content = $goodsContent->goods_content;
            }else{

                $goods_content = '';
            }//end if()

            $goods['goods_content']=$goods_content;

            $goodsGallery = GoodsGallery::findOrNew($goods->goods_id);

            $cat_id = $goods->cat_id;

            $categoryBrand = CategoryBrand::where('cat_id', $cat_id)->get();

            //$brandInfo = Brand::all();

            $brandArr = ['0'=>'=请选择品牌='];

            foreach ($categoryBrand as $key => $value) {

                $brand_id = $value->brand_id;

                $brand_name = Brand::find($brand_id)->brand_name;

                $brandArr[$brand_id] = $brand_name;
            }//end foreach()

            //店铺数组
            $shopInfo = Shop::all();

            $shopArr = ['0'=>'=选择店铺='];

            foreach ($shopInfo as $key => $value) {

                $shopArr[$value->id] = $value->shop_name;
            }//end foreach()

            $typeArr = ['0'=>'一般商品', '1'=>'e贸易商品'];

            return view('shop_admin.goods.edit', compact(['goods','goodsEorderInfo','category', 'brandArr','goodsGallery','shopArr','typeArr', 'back_url']));

        }//end if()

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id, GoodsUpdateRequest $goodsRequest,SolrService $solrService,CategoryService $categoryService)
    {

        //验证带E贸易请求
        if ($goodsRequest->type){

            new GoodsEorderInfoRequest();
        }

        $goodsInfo = Goods::find($id);

        $goods_name = $goodsRequest->goods_name;

        $goods_name = preg_replace('~\s{2,}~', ' ', $goods_name);       //将商品名字中间多个空格替换为一个空格

        $goodsRequest['goods_name'] = $goods_name;


        //更新主表
        $goodsInfo->update($goodsRequest->all());

        $this->dispatch(

            new OperationLogCommand('修改商品','Goods','goods_id:'.$id)
        );

        $goodsInfo->audit_status=0;

        $goodsInfo->is_on_sale=2;

        $goodsInfo->save();


        //更新goods_content
        $goods_id = $goodsInfo->goods_id;

        $cat_id = $goodsInfo->cat_id;

        $brand_id = $goodsInfo->brand_id;

        $keywords = $goodsInfo->keywords;


        $goods_content = @$goodsRequest->goods_content;

        $goodsContent = GoodsContent::find($goods_id);

        if($goodsContent){

            $goodsContents = GoodsContent::where('goods_id', $goods_id)->update(['goods_content'=>$goods_content]);
        }else{

            $goodsContents = GoodsContent::insert(['goods_id' => $goods_id, 'goods_content' => $goods_content]);
        }//end if()


        //更新相册
        if ($goods_id){

            $goodsGallery=GoodsGallery::findOrNew($goods_id);

            $goodsGallery->update($goodsRequest->get('goods_gallery'));
        }//end if()


        $category = Category::find($cat_id);

        if(!count($category)){

            $cat_id = 0;
        }//end if()


        $brand = Brand::find($brand_id);

        if(!count($brand)){

            $brand_id = 0;
        }//end if()

        if(!empty($keywords)){

            $keywords = preg_replace("/((\n)|(\s)|(\t)|(，))/", ',', $keywords);

            $keywords = trim($keywords, ',');

            $keywordsStr = trim($keywords);
        }else{

            $keywordsStr = '';
        }//end if()

        $this->keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService);

        //SOLR同步数据
        $solrService->update($goodsInfo);

        $pre_url = @$goodsRequest->pre_url;

        if($pre_url){

            return Redirect($pre_url);
        }else{

            return Redirect('shop_admin/goods/');
        }

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id,SolrService $solrService)
    {

        DB::beginTransaction();

        try {

            $goodsInfo = Goods::find($id);

            $goodsInfo->delete();

            $this->dispatch(

                new OperationLogCommand('删除商品','Goods','goods_id:'.$id)
            );

            $this->delKeywords($id);

            ActivityGoods::where('goods_id', $id)->delete();

            GoodsStockHistory::where('goods_id', $id)->delete();

            $solrService->delete($goodsInfo->goods_id);

            ProductSku::where('goods_id', $id)->delete();

        } catch (Exception $e) {

            DB::rollback();

            throw new Exception("删除商品失败");
        }//end try

        DB::commit();

        return Redirect('shop_admin/goods');

    }

    /**
     * 根据商品删除商品的搜索关键词
     *
     *
     * @date 2016/06/01
     * @author Leen
     */
    public function delKeywords($goods_id)
    {
        SearchKeywords::where('goods_id', $goods_id)->delete();

    }//end func delKeywords

    /**
     * 编辑更新商品
     *
     *
     * @date 2015/12/10
     * @author Leen
     */
    public function updateOne($id, Request $request)
    {

        $goods = Goods::find($id);

        if ($goods->is_on_sale==1){

            $goods->is_on_sale=2;

        }else{

            $goods->is_on_sale=1;

        }

        $goods->save();

        $this->dispatch(

            new OperationLogCommand('切换商品上下架','Goods','goods_id:'.$id)
        );

        $return['is_on_sale']=$goods->is_on_sale;

        return Response()->json($return);
    }

    /**
     * 编辑更新商品是否首页推荐,是否分类推荐
     *
     *
     * @date 2015/12/17
     * @author Leen
     */
    public function updateTwo($id, $name)
    {

        $goods = Goods::find($id);

        if ($goods->$name==1){

            $goods->$name=0;

        }else{

            $goods->$name=1;

        }

        $goods->save();

        $return[$name]=$goods->$name;

        return Response()->json($return);
    }




    /**
     * 添加商品搜索关键词
     *
     *
     * @date 2015/12/09
     * @author Leen
     */
    public function keywords($goods_id, $keywordsStr, $cat_id, $brand_id,$categoryService)
    {

        if(empty($goods_id)){

            return false;
        }//end if()

        $brand = Brand::find($brand_id);

        if ($brand){

            $keywordsStr.=','.$brand->brand_name;
        }

        $path = $categoryService->getPath($cat_id);

        foreach ($path as $category){

            if ($category) $keywordsStr.=','.$category->cat_name.','.$category->keywords;
        }

        $goods = Goods::find($goods_id);

        $goods->search_keywords = $keywordsStr;

        $goods->save();
    }

    /**
     * 商品入库、出库
     *
     *
     * @date 2016/02/16
     * @author Leen
     */
    public function updateStock($goods_id, GoodsStockOpreationRequest $request, StockService $stockService, GoodsStockHistoryService $goodsStockHistoryService)
    {

        $return = ['status'=>1, 'message'=>'', 'data'=>''];

        $goods_stock = $request->goods_stock;

        $operation = $request->operation;

        $user_id = Auth::user()->id;

        if($operation=='plus'){

            $describe = '增加库存，数量：'.$goods_stock;
        }elseif($operation=='reduce'){

            $describe = '减少库存，数量：'.$goods_stock;
        }//end if()

        try {

            $stockService->updateStock($goods_id, $user_id, $goods_stock, $operation, $describe, $goodsStockHistoryService);

        } catch (StockServiceException $e) {

            $return['status'] = 0;

            $return['message'] = $e->getMessage();

            return Response()->json($return);
        }
        $pre_url = @$request->pre_url;

        if($pre_url){

            $return['data'] = $pre_url;

            // return Redirect($pre_url);
        }else{

            $return['data'] = 'admin/goods';

            // return Redirect('shop_admin/goods');
        }

        return Response()->json($return);

    }//end func store()
}
